<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/11/8
 * Time: 13:36
 */

namespace app\index\controller;
use app\index\base_controller\BaseController;
use app\index\table\BookAlterTable;
use app\index\table\BookTable;
use think\Db;
use think\Exception;

class Book extends BaseController{

    public function bookTest(){
        $data = BookTable::table()->find();
        dump($data);
    }

    /**
     * page--基本信息
     */
    public function bookList(){
        return view('book_list');
    }

    /**
     * action--获取信息
     */
    public function getBookList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'BOOK_NO desc';
        }

        $condition = BookTable::getSessionConditions();
        try{
            $listSql = BookTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = BookTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page--新增
     */
    public function addPage(){
        $config = BookTable::getConfigAdd();
        $data = null;
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('book_add');
    }

    /**
     * action 新增
     */
    public function add() {
        $data = input();
        try{
            BookTable::add($data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * action 删除
     */
    public function deleteAll(){
        $list = input('list');
        Db::startTrans();
        try{
            foreach ($list as $bookNo){
                BookTable::delete(['BOOK_NO'=>$bookNo]);
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--编辑
     */
    public function editPage(){
        $bookNo = input('bookNo');
        $config = BookTable::getConfigEdit();
        $data = BookTable::get($bookNo);
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('book_edit');
    }

    /**
     * 编辑
     */
    public function edit() {
        $bookNo = input('BOOK_NO');
        $data = input();
        try{
            BookTable::update(['BOOK_NO'=>$bookNo],$data);
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--高级查询
     */
    public function searchPage(){
        $this->view->engine->layout('layout_popup');
        return view('book_search');
    }

    /**
     * page 新增变动
     */
    public function addAlterPage(){
        $idStr = input('idList');
        $bookList = BookTable::table()->where([['BOOK_NO','in',$idStr]])->select();
        if(empty($bookList)){
            return '查询图书信息失败';
        }
        $this->assign('bookIds',$idStr);
        $this->assign('bookList',$bookList);
        $this->view->engine->layout('layout_popup');
        return view('book_alter_add');
    }

    /**
     * action 新增变动
     */
    /**
     * 新增变动
     */
    public function addAlter(){
        $bookIds = input('bookIds');
        $bookArr = explode(',',$bookIds);

        try{
            Db::startTrans();
            foreach ($bookArr as $bookNo){
                $book = BookTable::get($bookNo);

                if(empty($book)){
                    Db::rollback();
                    return json_encode(['code'=>'0','msg'=>"查询图书[$bookNo]失败"]);
                }

                BookAlterTable::add([
                    'BOOK_NO'=>$bookNo
                    ,'ALTERTYPE_ID'=>'57'
                    ,'ALTER_DATE'=>input('ALTER_DATE')
                    ,'ALTER_VALUE'=>input('ALTER_VALUE')
                    ,'ALTER_NUM'=>input('ALTER_NUM')
                    ,'PASS_DEPART'=>input('PASS_DEPART')
                    ,'PASS_NO'=>input('PASS_NO')
                    ,'PASS_PERSON'=>input('PASS_PERSON')
                    ,'RELEVANT_DEPART'=>input('RELEVANT_DEPART')
                    ,'ALL_FEE'=>input('ALL_FEE')
                    ,'WORK_PERSON'=>input('WORK_PERSON')
                    ,'REMARK'=>input('REMARK')
                ]);

                BookTable::update(['BOOK_NO'=>$bookNo],[
                    'BOOK_NUM'=>$book['BOOK_NUM'] - input('ALTER_NUM')
                    ,'BOOK_FEE'=>$book['BOOK_FEE'] - input('ALTER_VALUE')
                ]);
            }
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'操作成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * page--变动信息
     */
    public function bookAlterList(){
        return view('book_alter_list');
    }

    /**
     * action--获取变动信息
     */
    public function getBookAlterList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'BOOK_NO desc';
        }

        $condition = null;
        $listCondition = Login::getListConditionBookAlter();
        if (!empty($listCondition['BOOK_NO'])) {
            $value = $listCondition['BOOK_NO'];
            $condition[] = ['BOOK_NO','like',"$value%"];
        }

        if (!empty($listCondition['ALTER_DATE_START'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_START']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','>=',$value];
        }
        if (!empty($listCondition['ALTER_DATE_END'])) {
            $value = Db::raw("to_date('{$listCondition['ALTER_DATE_END']}','yyyy-mm-dd')");
            $condition[] = ['ALTER_DATE','<=',$value];
        }
        try{
            $listSql = BookAlterTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->fetchSql()->select();
            $list = Db::query($listSql);
            $totalSql = BookAlterTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            return ['rows'=>$list,'total'=>$total[0]['TP_COUNT']];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * page 查看变动
     */
    public function alterEditPage(){
        $alterNo = input('alterNo');
        $alterInfo = BookAlterTable::get($alterNo);
        if(empty($alterInfo)){
            return '查询变动信息失败';
        }
        $this->assign('data',$alterInfo);

        $bookList = BookAlterTable::table()->find();
        $this->assign('bookList',$bookList);

        $this->view->engine->layout('layout_popup');
        return view('book_alter_edit');
    }



    /**
     * 打印
     */
    public function printPage() {
        $id = input('id');
        $data = BookTable::get($id);
        if(empty($data)){
            return '查询图书信息失败';
        }
        $config = BookTable::getConfigPrint();
        $this->assign('config',$config);
        $this->assign('data',$data);
        $this->view->engine->layout('layout_popup');
        return view('book_print');
    }


    public function addConditionSession() {
        $condition = input();
        Login::setListConditionBook($condition);
        return json_encode(['code'=>'200']);
    }

    public function alterSearchPage() {
        $this->view->engine->layout('layout_popup');
        return view('book_alter_search');
    }

    public function addSessionAlter() {
        $condition = input();
        Login::setListConditionBookAlter($condition);
        return json_encode(['code'=>'200']);
    }

    public function importPage() {
        $this->view->engine->layout('layout_popup');
        return view('import');
    }

    public function import() {
        $inputData = input('data');
        $postData = base64_decode($inputData);
        $list = json_decode($postData,true);
        $start = input('start');

        Db::startTrans();
        $fieldList = BookTable::BOOK_FIELD_LIST;
        $fieldCount = count($fieldList);
        foreach ($list as $key => $row) {
            $data = [];

            // 字段赋值
            $i = 0;
            foreach ($row as $key1=>$value) {
                $data[$fieldList[$i]] = $value;
                $i++;
                if ($i>=$fieldCount) {
                    break;
                }
            }

            try{
                BookTable::addImport($data);
            }
            catch (Exception $e){
                Db::rollback();
                return json_encode(['code'=>'0','msg'=>"第".($key + $start)."行数据写入出错",'data'=>$e->getMessage()]);
            }
        }

        Db::commit();
        return json_encode(['code'=>'200','msg'=>'导入成功']);
    }

    /**
     * page 图书导出页面
     */
    public function exportExcelPage() {
        $condition = BookTable::getSessionConditions();

        try{
            $totalSql = BookTable::table()->where($condition)->fetchSql()->count();
            $total = Db::query($totalSql);
            $total = $total[0]['TP_COUNT'];
            $this->assign('total',$total);

            $arr = $this->getDownLoadList($total);
            $this->assign('downList',$arr);

            $this->view->engine->layout('layout_popup');
            return view('export_excel');
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * action 图书导出Excel
     */
    public function exportExcel(){
        $sortStr = 'BOOK_NO desc';
        $start = input('start');
        $startL = $start-1;
        $end = input('end');
        $endL = $end-$start+1;

        $condition = BookTable::getSessionConditions();

        try{
            $listSql = BookTable::table()->where($condition)->limit($startL,$endL)->order($sortStr)->fetchSql()->select();
            $list = Db::query($listSql);
            BookTable::exportExcel($list,"图书$start-$end");
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * 标签打印
     */
    public function printTip() {
        $data['college'] = '资产处';
        $data['department'] = '供应科';
        $data['name'] = '微型电子计算机';
        $data['number'] = '20116567';
        $data['sn'] = '4F7C9';

        $this->assign('data',$data);

        $this->view->engine->layout('layout_popup');
        return view('book_tip_print');
    }




}